'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 一键出售道具
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var propertyConf = require('../../../../config/propertyConf');
var roleService = require('../../../../services/roleService');
var PlayerManager = require('../../../../libs/playerManager');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var property_id_list = msg.property_id_list || [];

    if (!property_id_list) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var sell_property_id;
    var reward = [];
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['bag', 'role', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var bag_model = player_manager.bag;

                var total_gold = 0;
                for (var i = property_id_list.length - 1; i >= 0; i--) {

                    // 判断物品是否存在
                    var property_id = property_id_list[i];
                    var property = bag_model.getProperty(property_id);
                    if (!property) {
                        return next(null, {
                            code: Code.BAG_ITEM_NOT_EXIST
                        });
                    }

                    // 获取物品的类型,根据物品类型去查询物品的价格
                    var property_type = property.getType();
                    var add_gold = propertyConf.getPropertySellGold(property_type) * property.getStackNum();

                    // 删除物品
                    sell_property_id = property.getId();
                    bag_model.removeProperty(property.getId());

                    roleService.addGoldLimit(player_manager, moduleType.MDL_BAG, operationType.OPR_BAG_USE_CONSUME, add_gold, property_type);
                    total_gold += add_gold;
                }
                reward.push({
                    reward_type: 1,
                    reward_num: total_gold,
                });
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward: reward
                }
            });
        }
    );
};
